/**
 * 
 */
package bot;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
/**
 * @author Philip
 *
 */
public class IRCServerConnection {
	private String server;
	private int port;

	private Socket socket;
	private BufferedReader input;
	private BufferedWriter output;

	/**
	 * Creates an IRC server connection
	 * 
	 * @param server
	 *            - Name of the IRC server
	 * @param port
	 *            - The port the server will connect to
	 */
	public IRCServerConnection(String server, int port) {
		this.server = server;
		this.port = port;
	}

	/** Connects to the server */
	public void connect() {
		try {
			socket = new Socket(server, port);
			socket.setSoTimeout(240000);
			
			InputStreamReader isr = new InputStreamReader(socket.getInputStream(), "UTF8");
			OutputStreamWriter isw = new OutputStreamWriter(socket.getOutputStream(), "UTF8");
			
			input = new BufferedReader(isr);
			output = new BufferedWriter(isw);
			
		} catch (Exception e) {
			
		}
	}
	
	public boolean isConnected() {
		return !socket.isClosed();
	}
	
	public void close() {
		try {
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/** Reads the next incoming line from the IRC server */
	protected String readLine() {
		String line = null;
		try {
			line = input.readLine();
		} catch (Exception e) {
			try {
				socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		return line;
	}

	/**
	 * Writes a line to the server
	 * 
	 * @param line
	 *            - The line that the server will receive
	 */
	public void write(String line) {
		try {
			output.write(line + "\n");
			output.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public String getServer() {
		return server;
	}
}
